package com.link.wseller.serive.impl;

import com.link.wseller.domain.ProductInfo;
import com.link.wseller.enums.SellNum;
import com.link.wseller.exception.SellException;
import com.link.wseller.mapper.ProductInfoMapper;
import com.link.wseller.mapper.impl.ProductInfoMapperImpl;
import com.link.wseller.serive.ProductInfoSerivce;
import dto.CartDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 商品业务
 */
@Service
public class ProductInfoServiceImpl implements ProductInfoSerivce {

    @Autowired
    private ProductInfoMapperImpl productInfoMapper;

    @Override
    public void increaseStock(List<CartDTO> cartDTOList) {

    }

    @Override
    @Transactional
    public void decreaseStock(List<CartDTO> cartDTOList) {

        for (CartDTO cartDTO: cartDTOList){

            ProductInfo productInfo = productInfoMapper.selectByPrimaryKey(cartDTO.getProductId());

            if (productInfo == null){
                throw new SellException(SellNum.PRODUCT_NOT_EXIST);
            }
            Integer result = productInfo.getProductStock() - cartDTO.getProductQuantity();
            if (result < 0){
                throw new SellException(SellNum.PRODUCT_STOCK_ERROR);
            }

            productInfo.setProductStock(result);
            productInfoMapper.updateByPrimaryKeySelective(productInfo);
        }
    }

    @Override
    public ProductInfo findOne(String productId) {
        return productInfoMapper.selectByPrimaryKey(productId);
    }

    @Override
    public List<ProductInfo> findUpAll() {
        return productInfoMapper.selectByProduct();
    }

    @Override
    public List<ProductInfo> findAll(Integer page, Integer size) {
        return productInfoMapper.selectByProductInfoStatus(page * size, size);
    }

    @Override
    public int saveProduct(ProductInfo productInfo) {
        return productInfoMapper.insert(productInfo);
    }

    @Override
    public int deleteByproductInfoId(String productInfoId) {
        return productInfoMapper.deleteByPrimaryKey(productInfoId);
    }

    @Override
    public int onSale(String productId) {
        return productInfoMapper.updateOffSaleStatus(productId);
    }

    @Override
    public int offSale(String productId) {
        return productInfoMapper.updateOffSaleStatus(productId);
    }

    @Override
    public int updateByProductId(ProductInfo productInfo) {
        return productInfoMapper.updateByPrimaryKey(productInfo);
    }
}
